package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    //获取业务层对象
    @Autowired
    private CategoryService categoryService;
    //获取会话域对象
    @Autowired
    private HttpSession session;

    //添加菜系
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        //获取会话id
        Long id = (Long) session.getAttribute("employee");
        //完善信息
        category.setCreateUser(id);
        category.setUpdateUser(id);
        //调用业务信息
        categoryService.save(category);
        return R.success("添加成功");
    }

    //分页查询
    @GetMapping("/page")
    public R<Page<Category>> findAll(Integer page, Integer pageSize) {
        //调用业务层查询方法
        Page<Category> categoryPage = categoryService.findAll(page, pageSize);
        //返回结果
        return R.success(categoryPage);
    }

    //修改套餐名或者菜系名
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        //获取会话id
        Long id = (Long) session.getAttribute("employee");
        //完善信息
        category.setUpdateUser(id);
        //调用修改业务信息
        boolean flag = categoryService.update(category);
        if (flag) {
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }

    //删除分类信息
    @DeleteMapping
    public R<String> delete(Long id) {
        if (categoryService.delete(id)) {
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    //根据类型查询分类列表信息
    @RequestMapping("/list")
    public R<List<Category>> findAllByPage(Integer type){
        //调用业务层查询方法
        List<Category> categoryList = categoryService.findAllByPage(type);
        return R.success(categoryList);
    }

}
